package com.blackhorse.service.impl;

import com.blackhorse.dao.AccountDao;
import com.blackhorse.domain.Account;
import com.blackhorse.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service("accountService")
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao;

    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
    public List<Account> findAll() {
        System.out.println("业务层：查询所有账户...");
        return accountDao.findAll();
    }

    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
    public Account findById(int id) {
        System.out.println("业务层：根据id查询账户..." + id);
        return accountDao.findById(id);
    }

    @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
    @Override
    public void saveAccount(Account account) {
        System.out.println("业务层：保存账户...");
        accountDao.saveAccount(account);
    }

    @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
    @Override
    public void updateAccount(Account account) {
        System.out.println("业务层：更新账户...");
        accountDao.updateAccount(account);
    }

    @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
    @Override
    public void transfer(int srcId, int tarId, float money) {
        System.out.println("业务层：转账..." + money);
        Account srcAccount = accountDao.findById(srcId);
        Account tarAccount = accountDao.findById(tarId);
        srcAccount.setMoney(srcAccount.getMoney() - money);
        tarAccount.setMoney(tarAccount.getMoney() + money);

        accountDao.updateAccount(srcAccount);
        //制造异常，判断事务是否回滚
        int a = 1 / 0;
        accountDao.updateAccount(tarAccount);
    }
}
